package com.wpf.system.controller;

import cn.hutool.core.convert.Convert;
import com.wpf.system.common.response.ResultUtils;
import com.wpf.system.common.response.ResultVO;
import com.wpf.system.entity.vo.CascaderVO;
import com.wpf.system.entity.Department;
import com.wpf.system.service.DepartmentService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/api/dept")
public class DeptController {

    @Resource
    DepartmentService departmentService;

    @GetMapping("/list")
    public List<Department> getDeptList(){
        return departmentService.getDeptList();
    }

    @GetMapping("/list/{id}")
    public Department getDeptById(@PathVariable("id") Long id){ return departmentService.getById(id); }

    @GetMapping("/plist")
    public List<CascaderVO> getParentDeptList(){
        return departmentService.getParentDeptList();
    }

    @PreAuthorize("hasAuthority('sys:dept:add')")
    @PostMapping
    public ResultVO addDept(@RequestBody Department dept){
        if (departmentService.save(dept)){
            return ResultUtils.success("添加组织成功！");
        }else{
            return ResultUtils.error("添加组织失败！");
        }
    }

    @PreAuthorize("hasAuthority('sys:dept:edit')")
    @PutMapping
    public ResultVO editDept(@RequestBody Department dept){
        if (departmentService.updateById(dept)){
            return ResultUtils.success("修改组织成功！");
        }else{
            return ResultUtils.error("修改组织失败！");
        }
    }

    @PreAuthorize("hasAuthority('sys:dept:delete')")
    @DeleteMapping("/{id}")
    public ResultVO deleteDept(@PathVariable("id") Long id){
        if (Convert.toBool(departmentService.deleteDeptById(id))){
            return ResultUtils.success("删除组织成功！");
        }else{
            return ResultUtils.error("删除组织失败！");
        }
    }

}
